#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QMutex>
#include "networkmanager.h"
#include "videocontroller.h"
#include "videoimageprovider.h"
#include "userdatabase.h"

// 远程视频图像提供者：供QML显示远程视频帧
class RemoteVideoImageProvider : public QQuickImageProvider
{
public:
    RemoteVideoImageProvider() : QQuickImageProvider(QQuickImageProvider::Image) {}

    // 添加设置远程视频帧的方法
    void setRemoteFrame(const QImage &frame)
    {
        QMutexLocker locker(&mutex); // 加锁保证线程安全
        remoteFrame = frame.copy();  // 复制帧数据
    }

    // 重写请求图像函数
    QImage requestImage(const QString &id, QSize *size, const QSize &requestedSize) override
    {
        Q_UNUSED(id)

        QMutexLocker locker(&mutex); // 加锁保证线程安全

        QImage resultFrame;
        if (remoteFrame.isNull())
        { // 如果没有远程帧，返回默认占位图像
            static QImage placeholder(640, 480, QImage::Format_RGB888);
            placeholder.fill(Qt::darkGray);
            resultFrame = placeholder;
        }
        else
        {
            resultFrame = remoteFrame; // 使用远程帧
        }

        // 如果请求了特定大小，则缩放图像
        if (requestedSize.isValid() && requestedSize.width() > 0 && requestedSize.height() > 0)
        {
            resultFrame = resultFrame.scaled(requestedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        }

        // 设置大小信息
        if (size)
        {
            *size = resultFrame.size();
        }

        return resultFrame;
    }

private:
    QImage remoteFrame; // 远程视频帧
    QMutex mutex;       // 互斥锁保证线程安全
};

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv); // 创建应用程序对象

    // 注册NetworkManager到QML
    qmlRegisterType<NetworkManager>("NetworkManager", 1, 0, "NetworkManager");

    QQmlApplicationEngine engine; // 创建QML引擎

    // 创建各个核心对象
    VideoController *videoController = new VideoController(&app);                   // 视频控制器
    VideoImageProvider *imageProvider = new VideoImageProvider(videoController);    // 本地视频提供者
    RemoteVideoImageProvider *remoteImageProvider = new RemoteVideoImageProvider(); // 远程视频提供者
    NetworkManager *networkManager = new NetworkManager(&app);                      // 网络管理器
    UserDatabase *userDatabase = new UserDatabase(&app);                            // 用户数据库

    // 注册图像提供者到QML（供Image元素使用）
    engine.addImageProvider("videoprovider", imageProvider);
    engine.addImageProvider("remotevideoprovider", remoteImageProvider);

    // 连接视频帧接收信号到远程图像提供者（更新远程视频）
    QObject::connect(networkManager, &NetworkManager::videoFrameReceived,
                     [remoteImageProvider](const QImage &frame)
                     {
                         remoteImageProvider->setRemoteFrame(frame);
                     });

    // 连接视频帧捕获信号到网络发送（本地视频帧通过网络发送）
    QObject::connect(videoController, &VideoController::videoFrameCaptured,
                     networkManager, &NetworkManager::sendVideoFrame);

    // 暴露对象到QML上下文（供QML直接访问）
    engine.rootContext()->setContextProperty("videoController", videoController);
    engine.rootContext()->setContextProperty("networkManager", networkManager);
    engine.rootContext()->setContextProperty("userDatabase", userDatabase);

    // 连接QML引擎对象创建失败信号
    QObject::connect(
        &engine,
        &QQmlApplicationEngine::objectCreationFailed,
        &app,
        []()
        { QCoreApplication::exit(-1); },
        Qt::QueuedConnection);

    // 加载QML主界面
    engine.loadFromModule("Ui", "Main");
    return app.exec(); // 运行应用程序事件循环
}
